using System;
using System.Collections.Generic;
using System.Text;
using Xeml.Document;
using Mpi.Common.Collections;
using Xeml.Document.Contracts;

namespace Xeml.Sampling
{
    public class ParameterColumnEmitter : ColumnEmitter
    {
        public override void Emit(IDocument xemlDoc)
        {
            this._columns.Clear();
            foreach (TreeNode<StoryBase> sbNode in xemlDoc.StoryBoard)
            {
                ExtractCols(sbNode.Content);
            }
        }

        private void ExtractCols(StoryBase sb)
        {
            Dictionary<DynamicTerm, List<string>> parmAndContexts = sb.AllOverParameters();
            foreach (DynamicTerm p in parmAndContexts.Keys)
            {
                VariableColumn pc;
               
                pc = new VariableColumn();
                pc.ColumnLevel = ParameterColumnLevel.Parameter;
                pc.DataType = typeof(string);
                pc.Term = p;
                pc.IsContainerColumn = true;
                pc.Enabled = true;

                if (!this._columns.ContainsKey(pc.Name))
                    this._columns.Add(pc.Name, pc);
                else
                    pc = (VariableColumn)this._columns[pc.Name];
                foreach (string context in parmAndContexts[p])
                {
                    VariableColumn pc2 = new VariableColumn();
                    pc2.ColumnLevel = ParameterColumnLevel.Context;
                    pc2.DataType = typeof(string);
                    pc2.Term = p;
                    pc2.IsContainerColumn = true;
                    pc2.Context = context;
                    pc2.Enabled = true;
                    if (!pc.SubColumns.ContainsKey(pc2.Name))
                        pc.SubColumns.Add(pc2.Name, pc2);
                    else
                        pc2 = (VariableColumn)pc.SubColumns[pc2.Name];
                    Dictionary<TimeSpan, DynamicValueBase> vals = sb.HistoryValues(p.TermId, context);
                    foreach (DynamicValueBase vb in vals.Values)
                    {
                        VariableColumn pc3 = new VariableColumn();
                        pc3.ColumnLevel = ParameterColumnLevel.Time;
                        pc3.DataType = typeof(string);
                        pc3.Term = p;
                        pc3.IsContainerColumn = false;
                        pc3.Context = context;
                        pc3.Time = vb.Time;
                        pc3.Enabled = true;
                        if (!pc2.SubColumns.ContainsKey(pc3.Name))
                            pc2.SubColumns.Add(pc3.Name, pc3);
                       
                    }
                }

            }
        }

        public ParameterColumnEmitter()
        {
            base._columns = new Dictionary<string, Column>();
            base.name = "Variables";
        }
    }
}
